package com.iraeta.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iraeta.entity.Student;
import com.iraeta.entity.User;
import com.iraeta.entity.UserRole;
import com.iraeta.mapper.sys.UserMapper;
import com.iraeta.service.sys.IUserService;
import com.iraeta.uitl.Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public User getUserByWxuid(String wxuid) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("wxuid", wxuid);
        return baseMapper.selectOne(qw);
    }
    @Override
    public User getUserByPhone(String phone) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", phone);
        return baseMapper.selectOne(qw);
    }
    @Override
    public User getUserByUserName(String userName, String pwd) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userName", userName).eq("pwd", pwd);
        return baseMapper.selectOne(qw);
    }
    @Override
    public List<User> listUserByName(String name) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(name)){
            qw.like("name", name);
        }
        qw.gt("id", 0);
        return baseMapper.selectList(qw);
    }
    @Override
    public List<User> listOrgUserByName(Integer orgId, String name) {
        return baseMapper.listOrgUserByName(orgId, name);
    }

    /*user role相关  user set role*/
    @Transactional
    @Override
    public void saveUserRole(int userId, List<Integer> roleList) {
        for (Integer roleId : roleList) {
            if(baseMapper.selectByUserRole(userId, roleId) == null){
                UserRole userRole = new UserRole(userId, roleId);
                baseMapper.insertUserRole(userRole);
            }
        }
        String userRoleIdStr = Util.parseListToString(roleList);
        baseMapper.deleteUserRoleIdStr(userId, userRoleIdStr);
    }

    /*user role相关  role set user*/
    public List<User> listUserByRoleId(int roleId){
        return baseMapper.selectUserByRoleId(roleId);
    }

    /*user permission相关*/
    @Override
    public List<Integer> listUserPermissions(int userId) {
        return baseMapper.selectUserPermissions(userId);
    }
}
